package com.hstx.demo.mqtt;

import com.hstx.demo.mqtt.until.Log;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;

import java.io.IOException;

public class UiMainApp extends Application {
    private static ApplicationContext applicationContext;

    @Override
    public void init() {
        try {
            SpringApplicationBuilder builder = new SpringApplicationBuilder(DemoMqttServerApplication.class);
            applicationContext = builder.headless(false).web(WebApplicationType.NONE).run();
        } catch (Exception e) {
            Log.error(getClass(), e, "失败：初始化失败，退出应用程序");
            System.exit(0);
        }
    }

    @Override
    public void start(Stage primaryStage) {
        applicationContext.publishEvent(new ApplicationEvent(primaryStage) {
            @Override
            public Object getSource() {
                try {
                    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/com.hstx.demo.mqtt.controller.xml/UiMainController.fxml"));
                    fxmlLoader.setControllerFactory(param -> applicationContext.getBean(param));

                    primaryStage.setScene(new Scene(fxmlLoader.load()));
                    primaryStage.setOnShown(event -> {
                        fxmlLoader.getController();
                    });
                    primaryStage.setTitle("MQTT Demo服务端");
                    primaryStage.show();
                } catch (IOException e) {
                    Log.error(getClass(), e, "失败：初始化应用失败，退出应用程序");
                    System.exit(0);
                }
                return super.getSource();
            }
        });
    }
}
